<template>
  <div>

    <div class="top-panel__box">

      <el-form :model="dataForm" ref="dataForm" inline size="small" onsubmit="return false">
        <el-form-item>
          <el-button type="primary" @click="addRow()">
            <fa-icon class="fa-upload"/>
            新增
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-input placeholder="产品名/机构名" v-model="dataForm.name" maxlength="30" clearable/>
        </el-form-item>
        <el-form-item v-if="name==='Loan'">
          <el-cascader
            placeholder="请选择产品类型"
            :options="typeMap"
            v-model="dataForm.typeOptions" clearable>
          </el-cascader>

        </el-form-item>
        <el-form-item v-if="name==='Loan'">
          <el-select placeholder="请选择还款方式" v-model="dataForm.repaymentType" clearable>
            <el-option v-for="(value, key) in dicts['repayment_method'].childMap" :key="key" :label="value"
                       :value="key"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-cascader
            placeholder="请选择城市"
            :options="localMap"
            v-model="dataForm.selectedOptions" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-select placeholder="状态" v-model="dataForm.productStatus" clearable>
            <el-option v-for="(value, key) in dicts['corporation_status'].childMap" :key="key" :label="value"
                       :value="key"/>
          </el-select>

        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList(1)">
            <fa-icon class="fa-search"/>
            查询
          </el-button>
          <reset-button :dataForm.sync="dataForm" :fixedData="{pageNum: 1, pageSize: 20}"/>
        </el-form-item>

      </el-form>
    </div>
    <el-row class="table-top">
      <el-table :data="dataList" v-loading="tableLoading" tooltip-effect="light" class="tc-table" size="small">
        <el-table-column type="index" width="55" fixed="left" label="序号"></el-table-column>
        <template v-for="(column, index) in options">
          <el-table-column :prop="column.prop" :label="column.label" :key="index" :width="column.width"
                           :show-overflow-tooltip="true"/>
        </template>
        <el-table-column prop="operation" class-name="oper-col" label="操作" :width="260">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" plain @click="showDetail(scope.row)">详情</el-button>
            <el-button size="mini" type="primary" plain @click="editStatus(scope.row)">
              {{ scope.row.productStatus === 'OPEN' ? '下架' : '上架' }}
            </el-button>
            <el-button size="mini" type="danger" plain @click="deleteRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row class="pagination-top">
        <pagination :pageNum.sync="dataForm.pageNum" :curSizes.sync="dataForm.pageSize" :total="total"
                    @getList="getList"/>
      </el-row>
    </el-row>
    <el-dialog :key="JSON.stringify(editDialog)"
               :title="(isEdit?'编辑' : '新增')+(name==='Loan' ?'贷款' : '信用卡')+'产品'" :visible.sync="editDialog"
               width="70%"
               :close-on-click-modal="false">
      <AddCardProd v-if="name==='Card'" :edit-data="editData" @close="closeForm"/>
      <AddLoanProd v-if="name==='Loan'" :edit-data="editData" @close="closeForm"/>
    </el-dialog>
    <el-dialog :key="JSON.stringify(curRow)" :title="name==='Loan' ?'贷款产品详情' : '信用卡产品详情'"
               :visible.sync="detailDialog" width="70%"
               :close-on-click-modal="false">
      <CardProdDetail :key="curRow.productId" v-if="name==='Card'" :edit-data="curRow" @close="closeForm"/>
      <LoanProdDetail :key="curRow.productId" v-if="name==='Loan'" :edit-data="curRow" @close="closeForm"/>
      <el-button type="primary" @click="editRow(curRow)">
        修改产品信息
      </el-button>
      <el-button type="primary" @click="editStatus(curRow)">
        {{ this.curRow.productStatus === 'OPEN' ? '下架产品' : '上架产品' }}
      </el-button>
      <el-button type="primary" @click="deleteRow(curRow)">
        删除产品
      </el-button>
    </el-dialog>
  </div>
</template>


<script>
import {CONSTANT_OBJ} from '@/utils/constant'
import {common} from '@/utils/common'
import api from '../api'
import AddLoanProd from './AddLoanProd'
import AddCardProd from './AddCardProd'
import CardProdDetail from './CardProdDetail'
import LoanProdDetail from './LoanProdDetail'
import {mapState} from 'vuex'
import localMap from '../js/localMap.json'

export default {
  props: {options: Array, name: String},
  components: {AddLoanProd, AddCardProd, CardProdDetail, LoanProdDetail},
  data () {
    return {
      editDialog: false,
      detailDialog: false,
      tableLoading: false,
      isEdit: false,
      editData: {},
      curRow: {},
      localMap,
      typeMap: [],
      dataForm: {
        name: '',
        repaymentType: '',
        productStatus: '',
        productCategory: '',
        productSubCategory: '',
        admitArea: '',
        selectedOptions: [],
        typeOptions: [],
        pageNum: 0,
        pageSize: 10
      },
      dataList: [],
      total: 0
    }
  },
  mounted () {
    let dict = this.dicts['product_category'].childList.map(item => {
      let s = 'prod_sub_' + item.dictNo
      let map = (this.dicts[s] || {childMap: {}}).childList.map(item1 => {
        return {
          value: item1.dictNo,
          label: item1.dictName
        }
      })
      return {
        value: item.dictNo,
        label: item.dictName,
        children: map
      }
    })
    this.typeMap = dict

    this.getList()
  },
  methods: {
    // 获取列表数据
    getList (val) {
      let productType = this.name === 'Card' ? 'CREDIT' : 'LOAN'
      this.dataForm.pageNum = val || this.dataForm.pageNum
      this.tableLoading = true
      let dataForm = {productType, ...this.dataForm}
      if (dataForm.typeOptions && dataForm.typeOptions.length) {
        dataForm.productCategory = dataForm.typeOptions[0]
        dataForm.productSubCategory = dataForm.typeOptions[1]
      }
      if (dataForm.selectedOptions && dataForm.selectedOptions.length) {
        dataForm.admitArea = dataForm.selectedOptions.join('-')
      }

      console.log('dataForm', dataForm)
      api.queryByCondition(dataForm).then(res => {
        const {responseCode, data} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          data.list.forEach(ele => {
            this.convertDict('corporation_status', 'productStatus', ele)

            let productCategory = ele['productCategory']
            let productCategoryStr = (this.dicts['product_category'] || {childMap: {}}).childMap[productCategory]
            console.log('productCategory', 'prod_sub_' + (productCategory || 'car_loan'))
            let productSubCategory = (this.dicts['prod_sub_' + (productCategory || 'car_loan')] || {childMap: {}}).childMap[ele.productSubCategory]
            ele.newProductCategory = productCategoryStr + '/' + productSubCategory

            let {maxRate, minRate, interestRateType, repaymentType} = ele
            ele.newRepaymentType = (repaymentType || '').split(',').map(type => {
              return (this.dicts['repayment_method'] || {childMap: {}}).childMap[type]
            }).join(',')
            const convertRate = (rate) => {
              rate = rate || 0
              switch (interestRateType) {
                case 'month':
                  return (rate * 12).toFixed(2)+'%'
                case 'month_fee':
                  return (rate * 12 * 1.85).toFixed(2)+'%'
                default:
                  return rate.toFixed(2)+'%'
              }
            }

            if (maxRate) {
              ele.rateRange = convertRate(minRate) + '-' + convertRate(maxRate)
            } else {
              ele.rateRange = convertRate(minRate) + '起'
            }

          })
          this.dataList = data.list || []
          this.total = parseInt(data.total) || 0
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    convertDict (dictName, fieldName, item) {
      let newFieldName = 'new' + fieldName[0].toUpperCase() + fieldName.slice(1)
      item[newFieldName] = (this.dicts[dictName] || {childMap: {}}).childMap[item[fieldName]]
    },
    // 新增
    addRow () {
      this.editData = {}
      this.editDialog = true
      this.isEdit = false
    },
    editRow (row) {
      this.detailDialog = false
      this.isEdit = true
      this.editData = this.curRow
      this.editDialog = true
    },
    showDetail (row) {
      this.curRow = row
      this.editData = row
      this.detailDialog = true
    },
    // 编辑
    editStatus (row) {
      const {productId, productStatus} = row
      if (productStatus === 'OPEN') {
        common.confirmFn('下架后客经将无法查看该产品！', '确认下架？').then(res => {
          if (res) {
            api.editProductStatus({productId, productStatus: 'CLOSE'}).then(res => {
              this.successFn(res)
              this.detailDialog = false
            })
          }
        })
        return
      }
      api.editProductStatus({productId, productStatus: 'OPEN'}).then(res => {
        this.successFn(res)
        this.detailDialog = false
      })

    },
    contentSuccess (data) {
      if (!this.isEdit) {
        this.addSuccess(data)
      } else {
        this.editSuccess(data)
      }
    },
    // 编辑返回
    editSuccess (data) {
      api.putArticleData(data).then(res => {
        const {responseCode, responseMsg: message} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.$message({
            message,
            type: 'success'
          })
          this.editDialog = false
          this.getList(1)
        }
      })
    },
    addSuccess (data) {
      api.addArticle(data).then(res => {
        const {responseCode, responseMsg: message} = res
        if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
          this.$message({
            message,
            type: 'success'
          })
          this.editDialog = false
          this.getList(1)
        }
      })
    },
    // 删除
    deleteRow (row) {
      common.confirmFn('删除后将无法恢复！', '确认删除？').then(res => {
        if (res) {
          api.delProduct(row.productId).then(res => {
            this.successFn(res)
            this.detailDialog = false

          })
        }
      })
    },
    successFn (res, dialog) {
      const {responseCode, responseMsg: message} = res
      if (responseCode === CONSTANT_OBJ.RES_SUCCESS) {
        this.$message({
          message,
          type: 'success'
        })
        if (dialog) {
          this[dialog] = false
        }
        this.getList(1)
      }
    },
    closeForm () {
      this.getList(1)
      this.editDialog = false
    }
  },
  computed: {
    ...mapState({
      dicts: state => state.common.dicts
    })
  }
}
</script>

<style scoped lang="less">

</style>
